package com.xspace.android.xafcommon.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.CompoundButton;
import android.widget.RadioButton;

import com.xspace.android.xafcommon.util.LogUtil;

import com.xspace.android.xafcommon.R;

/**
 * Created by liuchen on 2016/12/19.
 */
public class RadioButtonWithBottomColor extends RadioButton implements CompoundButton.OnCheckedChangeListener {
    private Drawable slidingBlockDrawable; // 滑块
    private float underlineHeight = 6;

    public RadioButtonWithBottomColor(Context context) {
        super(context);
    }

    public RadioButtonWithBottomColor(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (attrs != null) {
            TypedArray attrsTypedArray = context.obtainStyledAttributes(attrs, R.styleable.PagerSlidingTabStrip);
            slidingBlockDrawable = attrsTypedArray.getDrawable(R.styleable.PagerSlidingTabStrip_slidingBlock);
            underlineHeight = attrsTypedArray.getDimension(R.styleable.PagerSlidingTabStrip_underlineHeight, 6.0f);
            attrsTypedArray.recycle();
        }
        setOnCheckedChangeListener(this);
    }


    public RadioButtonWithBottomColor(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        LogUtil.d("slidingBlockDrawable " + (slidingBlockDrawable == null));
        LogUtil.d("isChecked " + (isChecked()));
        LogUtil.d("slidingBlockDrawable " + (slidingBlockDrawable));
        if (slidingBlockDrawable != null) {
            LogUtil.d("left " + (slidingBlockDrawable.getBounds().left));
        }
        if (slidingBlockDrawable != null && isChecked()) {
            float slidingBlockLeft = getLeft();
            float slidingBlockRight = getRight();
            LogUtil.d("slidingBlockLeft " + (slidingBlockLeft));
            LogUtil.d("slidingBlockRight " + (slidingBlockRight));
            float width = slidingBlockRight - slidingBlockLeft;
            slidingBlockDrawable.setBounds(15, (int) (getHeight() - underlineHeight), (int) (width - 15), getHeight());
            LogUtil.d(" left " + slidingBlockDrawable.getBounds().left + " top " + slidingBlockDrawable.getBounds()
                    .top + " right " + slidingBlockDrawable.getBounds().right + " bottom " + slidingBlockDrawable
                    .getBounds().bottom);
            LogUtil.d("underlineHeight " + underlineHeight);
            slidingBlockDrawable.draw(canvas);
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        LogUtil.d(" isChecked " + isChecked);
        postInvalidate();
    }
}
